//
//  HandeAR+Private.m
//  HandeAR
//
//  Created by HandeIdealVision on 2017/11/2.
//  Copyright © 2017年 HandeIdealVison. All rights reserved.
//

#import "HandeAR+Private.h"
#import <Photos/PHPhotoLibrary.h>

NSNotificationName finishInitUnit = @"finishInitUnit";

#if defined(__cplusplus)
extern "C"{
#endif
    void didInitUnity(void);
    void triggerShareAction(const char ** _bytes,int _length);
    void onQRMessage(const char * _msg);
    void onFound(void);
    void onExitCurrentAR(void);
    void onSwitchUI(void);   //UI已经显示出来了
    void onError(int _erroCode);
    void onCloseCameraDevice(void);
    void onShowUI(void);
#if defined(__cplusplus)
}
#endif

BOOL isAlreadyExit = NO;        //是否退出到cear sence
BOOL isAlreadyInitCamera = NO;  //是否初始化camera
@implementation HandeAR (Private)

+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    static HandeAR *_instance;
    dispatch_once(&onceToken, ^{
        _instance = [[HandeAR alloc] init];
    });
    
    return _instance;
}

- (void)sendDataToUnity {
    NSString *arResourceURL = [self valueForKey:@"arResourceURL"];
    if (arResourceURL) {
        UnitySendMessage("UnityBridge", "OnReceiveHost", [arResourceURL UTF8String]);
    }
    
    BOOL loginStatus = [[self valueForKey:@"loginStatus"] boolValue];
    
    UnitySendMessage("UnityBridge", "OnGetLoginState", loginStatus ? "1" : "0");
    
    NSString *annualReport = [self valueForKey:@"annualReport"];
    if (annualReport) {
        UnitySendMessage("UnityBridge", "OnGetBillData", [annualReport UTF8String]);
    }
    
    NSString *publishTime = [self valueForKey:@"publishTime"];
    if (publishTime) {
        UnitySendMessage("UnityBridge", "OnGetConferenceDate", [publishTime UTF8String]);
    }
    
    NSString *layoutParam = [self valueForKey:@"layoutParam"];
    if (layoutParam) {
        UnitySendMessage("UnityBridge", "OnGetScreenHeight", [layoutParam UTF8String]);
    }
}

- (void)initUnity {
    if (isAlreadyExit == YES) {
        UnitySendMessage("UnityBridge", "OnEnter", "");
    }
}

- (void)showQR {
    UnitySendMessage("UnityBridge", "OnEnterQR", "");
}

- (void)showAR {
    UnitySendMessage("UnityBridge", "OnEnterAR", "");
}

- (void)clearUnity {
    UnitySendMessage("UnityBridge", "CloseCameraDevice", "");
    UnitySendMessage("UnityBridge", "OnExitAR", "");
    isAlreadyExit = YES;
}

- (void)pauseAudio {
    UnitySendMessage("UnityBridge", "PauseAudio", "");
}

- (void)unPauseAudio {
    UnitySendMessage("UnityBridge", "UnPauseAudio", "");
}

- (void)saveImage:(UIImage *)image {
    BOOL needSaved = [[self valueForKey:@"needSaved"] boolValue];
    if (needSaved) {
        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
        if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
            // 无权限
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"请前往设置->隐私->相册授权应用访问相册权限" preferredStyle:UIAlertControllerStyleAlert];
            [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"点击取消");
            }]];
            [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                
                if ([[UIApplication sharedApplication]canOpenURL:url]) {
                    if ([[UIApplication sharedApplication] respondsToSelector:@selector(openURL:options:completionHandler:)]) {
                        if (@available(iOS 10.0, *)) {
                            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
                                NSLog(@"ok");
                            }];
                        } else {
                            // Fallback on earlier versions
                            [[UIApplication sharedApplication] openURL:url];
                        }
                    }
                    else {
                        [[UIApplication sharedApplication] openURL:url];
                    }
                }
            }]];
            
            [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
        }
        else {
            UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
        }
    }
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
}

#if defined(__cplusplus)
extern "C"{
#endif
    void didInitUnity(void) {
        [[HandeAR sharedInstance] sendDataToUnity];
    }
    
    void triggerShareAction(const char ** _bytes,int _length) {
        id<HandeARDelegate> delegate = [HandeAR sharedInstance].delegate;
        if ([delegate respondsToSelector:@selector(triggerShareAction:)]) {
            NSData *src = [NSData dataWithBytes:(const void *)_bytes length:(sizeof(unsigned char) * _length)];
            UIImage *image = [[UIImage alloc] initWithData:src];
            [[HandeAR sharedInstance] saveImage:image];
            [delegate triggerShareAction:src];
        }
    }
    
    void onQRMessage(const char * _msg) {
        id<HandeARDelegate> delegate = [HandeAR sharedInstance].delegate;
        if ([delegate respondsToSelector:@selector(didOnFoundQR:)]) {
            NSString *str = [NSString stringWithUTF8String:_msg];
//            [delegate didOnFoundQR:str];
        }
    }
    
    void onFound(void) {
        id<HandeARDelegate> delegate = [HandeAR sharedInstance].delegate;
        if ([delegate respondsToSelector:@selector(didOnFoundAR)]) {
            [delegate didOnFoundAR];
        }
    }
    
    void onExitCurrentAR(void) {
        id<HandeARDelegate> delegate = [HandeAR sharedInstance].delegate;
        if ([delegate respondsToSelector:@selector(willShowARScan)]) {
//            [delegate willShowARScan];
        }
    }
    
    void onSwitchUI(void) {
        isAlreadyInitCamera = YES;
    }
    
    void onError(int _erroCode) {
        id<HandeARDelegate> delegate = [HandeAR sharedInstance].delegate;
        if ([delegate respondsToSelector:@selector(onUnityException:)]) {
            [delegate onUnityException:_erroCode];
        }
    }
    
    void onCloseCameraDevice(void) {
        
    }
    
    void onShowUI(void) {
        [[NSNotificationCenter defaultCenter] postNotificationName:finishInitUnit object:nil];
    }
    
#if defined(__cplusplus)
}
#endif
@end
